import Dep from "./Dep"

export default class Watcher {

  constructor(data, expr, cb) {
    this.data = data
    this.expr = expr
    this.cb = cb
    this.value = this.get()
  }

  get() {
    Dep.pushTarget(this)
    const value = Watcher.parsePath(this.data, this.expr)
    Dep.popTarget()
    return value
  }

  update() {
    const oldValue = this.value
    this.value = Watcher.parsePath(this.data, this.expr)
    if (typeof this.cb === 'function') this.cb.call(this.data, this.value, oldValue)
  }

  static parsePath(value, expr) {
    const keys = expr.split('.')
    for (const key of keys) {
      if (!value) return
      value = value[key]
    }
    return value
  }

}
